<template>
  <div class="drugStorage">
    <div class="drugStorage-page">
      <div class="drugStorage-page-content">
        <div class="drugStorage-page-form">
          <el-input
            style="width: 300px"
            placeholder="请输入内容"
            :suffix-icon="Search"
            v-model="filterText"
            @change="handlePageChange(1)"
            @blur="handlePageChange(1)"
          />
          <el-select
            placeholder="科室"
            style="width: 300px; margin-left: 20px"
            @change="handlePageChange(1)"
            clearable filterable
            v-model="deptId"
            class="shift-search-select"
          >
            <el-option
              v-for="item in deptList"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptId"
            />
          </el-select>
          <el-select
            v-model="roleId"
            clearable filterable
            class="m-2"
            placeholder="角色"
            @change="handlePageChange(1)"
            style="width: 300px; margin-left: 20px"
          >
            <el-option
              v-for="item in roleList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>

          <div class="drugStorage-page-form-right">
            <el-button
              type="primary"
              @click="onUpdated"
              v-btnPermission="'btn-emp-updata'"
              >+ 新增</el-button
            >
          </div>
        </div>
        <div class="drugStorage-page-table">
          <Table
            :columns="tableColumns"
            :loading="loading"
            :data-source="dataSource"
          />
        </div>
        <div class="drugStorage-page-pagination">
          <Pagination
            style="margin-left: auto"
            :count="total"
            :page-size="pageSize"
            :pageNo="currentPage"
            @onPagechange="handlePageChange"
            @onSizechange="handleSizeChange"
          />
        </div>
      </div>
    </div>
    <BottomDrawer
      :visible="passwordVisible"
      :width="449"
      title="修改密码"
      @close="passwordVisible = false"
    >
      <div style="overflow: hidden; padding-bottom: 20px">
        <PageForm
          ref="pageFormRef"
          :gutter="1"
          :width="'90px'"
          :labelPosition="'left'"
          :rules="updateRules"
          :list="updateList"
          :form-data="formUpdate"
        />
      </div>

      <template #footer>
        <div>
          <el-button size="" type="primary" @click="updateSubmit">
            确定
          </el-button>
          <el-button size="" @click="passwordVisible = false">取消</el-button>
        </div>
      </template>
    </BottomDrawer>
  </div>
</template>

<script setup lang="ts">
import { Search } from '@element-plus/icons-vue';
import { ElForm, ElMessage, ElMessageBox } from 'element-plus';
import type { PageFormList } from '@/types/PageForm';
import type { TableColumn } from '@/types/table';
import type { Employee, EmployeeQuery } from '@/types/employee';
import type { FormInstance, FormRules } from 'element-plus';
import type { Action } from 'element-plus';
import {
  getEmployeeList,
  empenable,
  empdisable,
  deleteEmployee,
  resetEmployeePassword,
} from '@/api/clinic';
import { ref } from 'vue';
import { updatePassword } from '@/api/individual/index';
import { MD5 } from 'crypto-js';
import { deptGetSelectList } from '@/api/account';
import { getRoleList } from '@/api/clinic/index';
import store from '@/store';
const userBase = store.useBaseDataStore();

//科室
const deptList = ref<any[]>([]);
const getDeptGetSelectList = async () => {
  let res = await deptGetSelectList();
   if(res.code != '200'){
            //ElMessage.error(res.msg);
            return
        }
  deptList.value = res.data;
};

//角色

const roleList = ref<any[]>([]);
const getRoleListApi = async () => {
  let res = await getRoleList({ pageNo: 1, pageSize: 999999 });
   if(res.code != '200'){
            //ElMessage.error(res.msg);
            return
        }
  res.data.list.forEach((item: any) => {
    item.label = item.roleName;
    item.value = item.roleId;
  });
  roleList.value = res.data.list;
};
getRoleListApi();

getDeptGetSelectList();

const loading = ref(false);
const dataSource = ref<Employee[]>([]); // 数据源
const updateRules = reactive<FormRules>({
  newPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请输入确认密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
  ],
});
const formUpdate = ref<any>({
  newPassword: '',
  confirmPassword: '',
  empId: '',
});
const updateList: PageFormList = [
  {
    list: [
      {
        span: 24,
        label: '新密码',
        prop: 'newPassword',
        component: 'input',
        componentProps: {
          width: '311px',
        },
      },
      {
        span: 24,
        label: '确认密码',
        prop: 'confirmPassword',
        component: 'input',
        componentProps: {
          width: '311px',
        },
      },
    ],
  },
];
const pageFormRef = ref();
const updateSubmit = async () => {
  const pageForm = pageFormRef.value.ruleFormRef;
  let data: any = {
    newPassword: MD5(formUpdate.value.newPassword).toString(),
    empId: formUpdate.value.empId,
    confirmPassword: MD5(formUpdate.value.confirmPassword).toString(),
  };
  await pageForm
    .validate()
    .then(async () => {
      const res = await resetEmployeePassword(data);
      if (res.code == '200') {
        ElMessage.success('修改成功');
        refreshEmployeeList();
        passwordVisible.value = false;
      } else {
        //ElMessage.error(res.msg);
      }
    })
    .catch(() => {});
};
const total = ref(0); // 总条数
const currentPage = ref(1); // 当前页
const pageSize = ref(10); // 每页条数
const filterText = ref('');
const empId = ref<any>('');
const deptId = ref<any>('');
const roleId = ref<any>('');
const passwordVisible = ref(false);
const tableColumns: TableColumn[] = [
  { prop: 'empId', label: '员工ID', width: 80 },
  { prop: 'empNo', label: '工号', width: 100 },
  { prop: 'empName', label: '员工名称', width: 120 },
  {
    prop: 'genderName',
    label: '性别',
    width: 80,
    componentProps: {
      formatter: (row) => {
        row.genderName = userBase.getEnumData(row.gender, 'genderEnum');
        return row.genderName;
      },
    },
  },
  {
    prop: 'isEnabledName',
    label: '在职状态',
    type: 'tag',
    width: 100,
    componentProps: {
      formatter: (row) => {
        row.isEnabledName = row.isEnabled === '1' ? '在职' : '离职';
        return row.isEnabledName;
      },
    },
  },
  { prop: 'phone', label: '手机号', width: 120 },
  { prop: 'deptName', label: '所属科室', width: 120 },
  { prop: 'title', label: '职称', width: 100 },
  {
    prop: 'isAdminName',
    label: '管理员',
    type: 'tag',
    width: 80,
    componentProps: {
      formatter: (row) => {
        row.isAdminName = row.isAdmin === '1' ? '是' : '否';
        return row.isAdminName;
      },
    },
  },
  { prop: 'roleList', label: '授权角色', width: 150 },
  { prop: 'idCard', label: '身份证号', width: 150 },
  { prop: 'solarBirthday', label: '阳历生日', width: 120 },
  { prop: 'hireDate', label: '入职日期', width: 120 },
  { prop: 'email', label: '邮箱', width: 180 },
  {
    prop: 'action',
    label: '操作',
    type: 'action',
    width: 170,
    componentProps: {
      fixed: 'right',
    },
    buttonGroup: [
      {
        label: '编辑',
        permissions: 'btn-emp-edit',
        type: 'text',
        click: (row: Employee) => {
          handleEdit(row);
        },
      },

      {
        label: '修改密码',
        type: 'text',
        statusName: ['isAdmin'],
        status: '0', // 当状态为管理员时显示修改密码按钮
        permissions: 'btn-emp-passWord',
        click: (row: Employee) => {
          formUpdate.value.empId = row.empId;
          passwordVisible.value = true;
        },
      },
      {
        label: '启用',
        permissions: 'btn-emp-enable',
        statusName: ['isEnabled','isAdmin'],
        status: '0,0', // 当状态为离职时显示启用按钮
        type: 'text',
        click: (row: Employee) => {
          handleEnableEmployee(row);
        },
      },
      {
        label: '停用',
        permissions: 'btn-emp-disable',
        statusName: ['isAdmin','isEnabled'],
        status: '0,1', // 当状态为在职时显示停用按钮
        type: 'text',
        color: '#D90000',
        click: (row: Employee) => {
          handleDisableEmployee(row);
        },
      },
      // {
      //   label: '删除',
      //   type: 'text',
      //   color: '#D90000',
      //   click: (row: Employee) => {
      //     handleDeleteEmployee(row);
      //   },
      // },
    ],
  },
];

//弹窗调用

const title = ref<string>('');
const handlePageChange = (page: number) => {
  //console.log('当前页:', page);
  currentPage.value = page;
  refreshEmployeeList();
};
const handleSizeChange = (size: number) => {
  //console.log('每页条数:', size);
  currentPage.value = 1;

  pageSize.value = size;
  refreshEmployeeList();
};
const handleClose = (e: string) => {
  //console.log(e, '父组件方法被调用');
};
const route = useRoute();

//console.log(route, 'route');

// 员工操作方法
const handleEdit = (row: Employee) => {
  //console.log('编辑员工:', row);
  title.value = '编辑员工';
  sessionStorage.setItem('empInfo', JSON.stringify(row));
  // navigateTo('/manage/managePages/clinic/empInfo?empId='+row.empId);
  navigateTo(
    '/manage/managePages/clinic/empInfo?menuId=' +
      route.query.menuId +
      '&' +
      'submenuId=' +
      route.query.submenuId +
      '&empId=' +
      row.empId
  );

  // dialogRef.value?.open1(row);
};

const handleEnableEmployee = async (row: Employee) => {
  try {
    // 这里调用启用员工的 API
    let res = await empenable({ empId: row.empId });
    if (res.code == '200') {
      ElMessage({
        type: 'success',
        message: '员工启用成功',
      });
      refreshEmployeeList();
    } else {
      // ElMessage({
      //   type: 'error',
      //   message: res.msg,
      // });
    }
  } catch (error) {
    //console.error('启用员工失败:', error);
    ElMessage({
      type: 'error',
      message: '启用员工失败',
    });
  }
};
const onUpdated = () => {
  navigateTo(
    '/manage/managePages/clinic/empInfo?menuId=' +
      route.query.menuId +
      '&' +
      'submenuId=' +
      route.query.submenuId
  );
};
const handleDisableEmployee = async (row: Employee) => {
  try {
    //console.log('停用员工:', row);
    // 这里调用停用员工的 API
    let res = await empdisable({ empId: row.empId });

    if (res.code == '200') {
      ElMessage({
        type: 'success',
        message: '员工停用成功',
      });
      refreshEmployeeList();
    } else {
      // ElMessage({
      //   type: 'error',
      //   message: res.msg,
      // });
    }
  } catch (error) {
    //console.error('停用员工失败:', error);
    ElMessage({
      type: 'error',
      message: '停用员工失败',
    });
  }
};

const refreshEmployeeList = async () => {
  // 查询员工列表
  const params = {
    empName: filterText.value,
    deptId: deptId.value,
    roleId: roleId.value,
    pageNo: currentPage.value,
    pageSize: pageSize.value,
  };
  loading.value = true;
  const res = await getEmployeeList(params);
  if(res.code != '200'){
    //ElMessage.error(res.msg);
    loading.value = false;
    return
  }
  for (let index = 0; index < res.data.list.length; index++) {
    let item = res.data.list[index];
    let roleList = '';
    item.roleList = item.roleList.map((role: any, index: number) => {
      if (index == item.roleList.length - 1) {
        roleList += role.roleName;
      } else {
        roleList += role.roleName + ',';
      }
    });
    item.roleList = roleList;
  }

  dataSource.value = res.data.list;
  total.value = res.data.totalCount;
  //console.log('获取员工列表:', res);
  loading.value = false;
};
onMounted(refreshEmployeeList);
const handleDeleteEmployee = (row: Employee) => {
  ElMessageBox.confirm(
    `确定要删除员工"${row.empName}"吗？删除后无法恢复。`,
    '删除员工',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
      confirmButtonClass: 'el-button--danger',
    }
  )
    .then(async () => {
      try {
        //console.log('删除员工:', row);
        // 这里调用删除员工的 API
        let res = await deleteEmployee({ empId: row.empId });

        if (res.code == '200') {
          ElMessage({
            type: 'success',
            message: '员工删除成功',
          });
        } else {

        }
      } catch (error) {
        //console.error('删除员工失败:', error);
        ElMessage({
          type: 'error',
          message: '删除员工失败',
        });
      }
    })
    .catch(() => {
      // 用户取消删除
    });
};
</script>

<style lang="scss" scoped>
.drugStorage {
  height: 100%;
}
.drugStorage-dialog {
  width: 80%;
  margin: 0 auto;
}
.drugStorage-page {
  background: #fff;
  border-radius: 6px;
  height: 100%;
  .drugStorage-page-nav {
    display: flex;
    align-items: center;
    justify-content: left;
    border-radius: 4px;
    border-bottom: 1px solid #e7e7e7;
    .el-dropdown-link {
      background: rgba(22, 173, 164, 0.08);
      border-radius: 0px 0px 0px 0px;
      padding: 16px 21px;
      cursor: pointer;
      color: var(--el-color-primary) !important;
      display: flex;
      font-size: 16px;
      align-items: center;
    }
  }
  .drugStorage-page-content {
    padding: 10px 24px;
    height: calc(100% - 64px);
    .drugStorage-page-form {
      display: flex;
      align-items: center;
      .drugStorage-page-form-right {
        margin-left: auto;
      }
    }
    .drugStorage-page-table {
      margin-top: 22px;
      height: calc(100% - 68px);
    }
    .drugStorage-page-pagination {
      margin-top: 24px;
      display: flex;
      align-items: center;
      .drugStorage-page-pagination-total {
        margin-right: auto;
        font-family: Microsoft YaHei, Microsoft YaHei;
        font-weight: 400;
        font-size: 14px;
        color: rgba(0, 0, 0, 0.6);
        text-align: left;
        font-style: normal;
        text-transform: none;
      }
    }
  }
}
</style>
